<script lang="ts" setup>
import { ref, nextTick, computed } from 'vue'
import { ElMessage, ElTree } from 'element-plus'
import wsjzglService from '@/api/wsjzgl'
import jyglService from '@/api/jygl'
import TreeUtilDTO from '@/utils/tree'
import { useMainStore } from '@/store/main'
import { mlxxMainStore } from '@/store/mlxx'
import printFn from '@/utils/print'
const mlxxStore = mlxxMainStore()

const props = defineProps({
  syfsmc: {
    type: String,
    required: true,
  },
})

const emit = defineEmits(['nodeClick', 'updatePage'])
const store = useMainStore()

const init = () => {
  queryTree()
  treeNodeData.value = {}
}

const filterForm = ref({
  gjzValue: '',
  mlSelect: '0',
})

const defaultProps = {
  children: 'children',
  label: 'mc',
}
const treeData = ref<any>([])
// const selectTreeData = ref<any>([])
const firtsNode = ref<any>()
/*
 * 查询树
 */
const queryTree = () => {
  const params = {
    ajbh: mlxxStore.daxqData?.ajbh as string,
    jysqbh: mlxxStore.daxqData?.jysqbh as string,
    mlxslx: '0',
  }
  jyglService
    .queryJyqsajmlList(params)
    .then((res) => {
      let obj = mlxxStore.daxqData
      const dbmNode = res.data?.find((item: any) => item.mc === '待编目材料')
      const zjNode = res.data?.find((item: any) => item.mc === '正卷')
      const fjNode = res.data?.find((item: any) => item.mc === '副卷')
      store.saveJzsmDbmNode(dbmNode)
      store.saveZjNode(zjNode)
      store.saveFjNode(fjNode)
      res.data?.forEach((item: any) => {
        if (!item.fbh) {
          item['fbh'] = obj.ajbh
        }
      })
      res.data.push({
        ajbhaj: obj.ajbh,
        bh: obj.ajbh,
        mc: obj.ajmc,
        wjsl: 0,
      })
      treeData.value = TreeUtilDTO.getTreeData(res.data, 'bh', 'fbh')
      treeData.value?.forEach((data: any) => {
        if (data.children && data.children?.length > 0) {
          data.children.forEach((data1: any) => {
            data.wjsl += data1.wjsl
            if (data1.children && data1.children.length > 0) {
              data1.children.forEach((data2: any) => {
                if (data1.bh === data2.fbh && data1.mc === '正卷') {
                  data2['zfj'] = '正卷'
                }
                if (data1.bh === data2.fbh && data1.mc === '副卷') {
                  data2['zfj'] = '副卷'
                }
              })
            }
          })
        }
      })
      if (treeData.value.length) {
        firtsNode.value = null
        // 递归选择第一个
        getFirstNode(treeData.value)
        if (firtsNode.value) {
          handleCheckNode(firtsNode.value)
        }
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

const getFirstNode = (arr: any[]) => {
  if (firtsNode.value) return
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].children && arr[i].children.length > 0) {
      getFirstNode(arr[i].children)
    } else {
      firtsNode.value = arr[i]
    }
    return
  }
}

const handleCheckNode = (node: any) => {
  nextTick(() => {
    treeNodeClick(node)
    treeRef.value!.setCurrentKey(node.bh)
  })
}

/*
 * 树节点点击（抛出方法到主界面）
 */
const treeNodeData = ref()
const treeNodeClick = (data: any) => {
  if (treeNodeData.value?.bh === data.bh) {
    return
  }
  treeNodeData.value = data
  if (data.ajbh !== store.$state.nodeTreeData?.ajbh) {
    const ml = TreeUtilDTO.findNode(treeData.value, data.ajbh, 'bh')
    emit('nodeClick', treeNodeData.value, ml?.children)
  } else {
    emit('nodeClick', treeNodeData.value)
    const params = {
      ajbh: data.ajbh,
      mlbh: data.bh,
    }
    wsjzglService
      .queryWjList(params)
      .then((res) => {
        nextTick(() => {
          if (res.data.length) {
            emit('updatePage', res.data[0].wjbh)
          }
        })
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
  }
}

// 抛出去刷新再请求一次方法
const againTreeData = () => {
  const params = {
    ajbh: mlxxStore.daxqData?.ajbh as string,
    jysqbh: mlxxStore.daxqData?.jysqbh as string,
    mlxslx: '0',
  }

  jyglService
    .queryJyqsajmlList(params)
    .then((res) => {
      let obj = mlxxStore.daxqData
      const dbmNode = res.data?.find((item: any) => item.mc === '待编目材料')
      const zjNode = res.data?.find((item: any) => item.mc === '正卷')
      const fjNode = res.data?.find((item: any) => item.mc === '副卷')
      store.saveJzsmDbmNode(dbmNode)
      store.saveZjNode(zjNode)
      store.saveFjNode(fjNode)
      res.data?.forEach((item: any) => {
        if (!item.fbh) {
          item['fbh'] = obj.ajbh
        }
      })
      res.data.push({
        ajbhaj: obj.ajbh,
        bh: obj.ajbh,
        mc: obj.ajmc,
        wjsl: 0,
      })
      treeData.value = TreeUtilDTO.getTreeData(res.data, 'bh', 'fbh')
      treeData.value?.forEach((data: any) => {
        if (data.children && data.children?.length > 0) {
          data.children.forEach((data1: any) => {
            data.wjsl += data1.wjsl
            if (data1.children && data1.children.length > 0) {
              data1.children.forEach((data2: any) => {
                if (data1.bh === data2.fbh && data1.mc === '正卷') {
                  data2['zfj'] = '正卷'
                }
                if (data1.bh === data2.fbh && data1.mc === '副卷') {
                  data2['zfj'] = '副卷'
                }
              })
            }
          })
        }
      })
      nextTick(() => {
        treeRef.value!.setCurrentKey(store.$state.nodeTreeData?.bh)
      })
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

const treeRef = ref<InstanceType<typeof ElTree>>()

// 文字过滤
const filterTree = () => {
  treeRef.value?.filter(filterForm.value.gjzValue)
}

/**
 * 树节点过滤
 */
const filterNode = (value: any, data: any) => {
  let flag = true
  if (value) {
    if (typeof value === 'string') {
      // 文字过滤
      flag = data[defaultProps.label].indexOf(value) !== -1
    }
  }
  return flag
}

// 下载
const downloaClick = () => {
  if (checkNodes.value.length === 0) {
    ElMessage({ type: 'warning', message: '请选择要下载的档案' })
    return
  }
  const params = {
    ajmc: mlxxStore.daxqData?.ajmc,
    mlList: checkNodes.value.map((item: any) => {
      return {
        ajbh: item.ajbh,
        ajmc: item.zfj,
        mlbh: item.bh,
      }
    }),
  }
  jyglService
    .downAjZip(params)
    .then((res: any) => {
      if (res) {
        if (res.data.type === 'application/json') {
          const reader = new FileReader()
          reader.onload = () => {
            const jsonData =
              typeof reader.result === 'string' ? JSON.parse(reader.result) : reader.result
            ElMessage({ type: 'warning', message: jsonData.message })
          }
          reader.readAsText(res.data)
        } else {
          const downloadElement = document.createElement('a')
          downloadElement.href = window.URL.createObjectURL(res.data)
          downloadElement.download = '案卷压缩包.zip'
          document.body.appendChild(downloadElement)
          downloadElement.click() //点击下载
          document.body.removeChild(downloadElement) //下载完成移除元素
        }
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

const checkNodes = ref<any[]>([])
// 树节点勾选事件
const checkChange = (data: any, checks: any) => {
  checkNodes.value = checks.checkedNodes.filter((item: any) => item.cj === '2')
}

const isShowCheckout = computed(() => {
  if (mlxxStore.daxqData?.showDownloadPrinting) {
    return true
  }
  return false
})

const print = () => {
  if (checkNodes.value.length === 0) {
    ElMessage({ type: 'warning', message: '请选择要打印的档案' })
    return
  }
  const params = {
    fileSource: '2',
    localFilePathList: [],
    fileName: '借阅档案.pdf',
    loadingHeader: {},
    loadingParam: {
      ajmc: mlxxStore.daxqData?.ajmc,
      mlList: checkNodes.value.map((item: any) => {
        return {
          mlbh: item.bh,
        }
      }),
    },
    loadingUrl: `${window.IPCONFIG}/api/jygl/downMlspdf`,
    requestMethodName: 'POST',
  }
  printFn(params)
}

defineExpose({ init, againTreeData })
</script>
<template>
  <div class="container">
    <div class="center">
      <el-row :gutter="10" style="align-items: center">
        <el-col :span="mlxxStore.daxqData?.showDownloadPrinting ? 12 : 24">
          <el-input
            v-model="filterForm.gjzValue"
            autosize=""
            placeholder="请输入查询关键字"
            @change="filterTree"
          >
            <template #suffix>
              <el-icon @click="filterTree" class="el-input__icon"><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="12" v-if="mlxxStore.daxqData?.showDownloadPrinting">
          <div style="display: flex">
            <button
              class="btn_operation"
              @click="downloaClick"
              :disabled="checkNodes.length === 0 || !props.syfsmc?.includes('下载')"
            >
              <div class="btn-bj" title="下载"></div>
              <span>下载</span>
            </button>
            <button
              class="btn_operation"
              @click="print"
              :disabled="checkNodes.length === 0 || !props.syfsmc?.includes('打印')"
            >
              <div class="btn-sbxz" title="打印"></div>
              <span>打印</span>
            </button>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="bottom">
      <!-- draggable -->
      <el-tree
        ref="treeRef"
        style="max-width: 600px"
        :data="treeData"
        node-key="bh"
        highlight-current
        default-expand-all
        :expand-on-click-node="false"
        :props="defaultProps"
        @node-click="treeNodeClick"
        :filter-node-method="filterNode"
        @check="checkChange"
        :show-checkbox="isShowCheckout"
      >
        <template #default="{ data }">
          <div class="custom-tree-node">
            <!-- <el-icon v-if="data.fbh"> <FolderOpened /></el-icon> -->
            <img v-if="!data.fbh" src="/src/assets/images/file-icon.png" alt="" />
            <img
              v-if="data.mc === '正卷' || data.mc === '副卷'"
              src="/src/assets/images/dbm.png"
              alt=""
            />
            <img v-if="data.mc === '待编目材料'" src="/src/assets/images/juan.png" alt="" />
            <img
              v-if="data.cj === '2' && data.sfdzajml === 'Y'"
              style="margin-right: 5px"
              src="/src/assets/images/xswjwyz.png"
              alt=""
            />
            <img
              v-if="data.cj === '2' && (data.sfzzajml === 'Y' || !data.sfzzajml)"
              src="/src/assets/images/xxwj.png"
              alt=""
            />
            <img
              v-if="data.cj === '2' && data.sfyy === 'Y'"
              style="margin-right: 5px"
              src="/src/assets/images/xsxwjyyz.png"
              alt=""
            />
            <span :class="data.cj === '2' ? 'over-title' : ''" :title="data.mc"
              >&nbsp;{{ data.mc }}&nbsp;</span
            >
            <span>({{ data.wjsl }})</span>
          </div>
        </template>
      </el-tree>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  // padding: 5px;
  .top {
    margin-bottom: 10px;
  }
  .center {
    padding-bottom: 10px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.15);
  }
  .bottom {
    height: calc(100% - 43px);
    overflow-y: auto;
    .tree_rightmenu {
      position: fixed;
      width: 120px;
      border: 1px solid rgba(0, 0, 0, 0.15);
      box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
      z-index: 1000;
      background-color: #fff;
      display: flex;
      flex-direction: column;
      align-items: center;
    }
  }
}
.add-aj {
  width: 100%;
}
.el-input__icon {
  cursor: pointer;
}

.custom-tree-node {
  width: calc(100% - 40px);
  display: flex;
  align-items: center;
  .over-title {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}

:deep(.el-tabs .el-tabs__content) {
  height: calc(100% - 40px);
  /* overflow: auto; */
  padding: 0;
}

.btn_operation {
  white-space: nowrap;
}
</style>
